package com.adk.backend.service.impl;

import com.adk.backend.entity.LxAdmin;
import com.adk.backend.mapper.AdminMapper;
import com.adk.backend.service.AuthService;
import com.adk.backend.service.PermissionService;
import com.adk.backend.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证服务实现类
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PermissionService permissionService;
    
    @Value("${jwt.password-key:bm}")
    private String passwordKey;
    
    @Override
    public Map<String, Object> login(String email, String password) {
        Map<String, Object> result = new HashMap<>();
        
        if (!StringUtils.hasText(email) || !StringUtils.hasText(password)) {
            result.put("success", false);
            result.put("message", "邮箱或密码不能为空");
            return result;
        }
        
        // 查询用户
        LxAdmin admin = adminMapper.selectByEmail(email);
        if (admin == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        
        // 验证密码（MD5加密：PASSWORD_KEY + password）
        String encryptedPassword = md5(passwordKey + password);
        if (!encryptedPassword.equals(admin.getAdminpwd())) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }
        
        // 检查状态
        if (admin.getStatus() != null && admin.getStatus() != 0) {
            result.put("success", false);
            result.put("message", "账户已被禁用");
            return result;
        }
        
        // 生成Token
        String token = jwtUtil.generateToken(admin.getId(), admin.getUsername(), admin.getUserType());
        
        // 更新最后登录时间（时间戳，秒）
        admin.setLastLogin((int) (System.currentTimeMillis() / 1000));
        adminMapper.updateById(admin);
        
        // 返回结果
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", admin.getId());
        userInfo.put("username", admin.getUsername());
        userInfo.put("email", admin.getEmail());
        userInfo.put("userType", admin.getUserType());
        userInfo.put("customerId", admin.getCustomerId());
        userInfo.put("whId", admin.getWhId());
        userInfo.put("avatar", admin.getAvatar());
        
        // 获取用户权限信息
        Map<String, Object> permissions = permissionService.getUserPermissions(admin.getUserType());
        userInfo.put("permissions", permissions);
        
        result.put("success", true);
        result.put("message", "登录成功");
        result.put("token", token);
        result.put("userInfo", userInfo);
        
        return result;
    }
    
    @Override
    public List<LxAdmin> getSalesUsers() {
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        // user_type in (4, 6, 35) 且 status=0
        wrapper.in("user_type", 4, 6, 35);
        wrapper.eq("status", 0);
        wrapper.orderByAsc("username");
        return adminMapper.selectList(wrapper);
    }
    
    @Override
    public LxAdmin getUserByToken(String token) {
        if (!StringUtils.hasText(token)) {
            log.warn("Token为空");
            return null;
        }
        
        try {
            // 先验证Token是否有效
            if (!jwtUtil.validateToken(token)) {
                log.warn("Token无效或已过期");
                return null;
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId != null) {
                LxAdmin admin = adminMapper.selectById(userId);
                if (admin == null) {
                    log.warn("用户不存在，userId: {}", userId);
                }
                return admin;
            } else {
                log.warn("无法从Token中获取用户ID");
            }
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
        }
        
        return null;
    }
    
    @Override
    public void logout(String token) {
        // 可以在这里实现Token黑名单机制，使用Redis存储
        // 目前简单实现，客户端删除Token即可
    }
    
    /**
     * MD5加密
     */
    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
}

